package xyz.hubery.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MP自动填充处理器
 */
@Component
@Slf4j
public class AutoFillHandler implements MetaObjectHandler {

    /**
     * 新增时自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getCurrentUserId();
        this.strictInsertFill(metaObject,"createBy", Long.class,userId);
        this.strictInsertFill(metaObject,"created", Date.class,new Date());
        this.strictInsertFill(metaObject,"lastUpdateTime", Date.class,new Date());
    }

    /**
     * 修改时填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getCurrentUserId();
        this.strictUpdateFill(metaObject,"modifyBy", Long.class,userId);
        this.strictUpdateFill(metaObject,"lastUpdateTime",Date.class,new Date());
    }

    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return getSystemUserId();
            }

            Object principal = authentication.getPrincipal();

            // 检查是否是匿名用户
            if ("anonymousUser".equals(principal.toString())) {
                return getSystemUserId();
            }

            // 检查是否是服务账户（客户端凭证）
            String principalStr = principal.toString();
            if ("inside-app".equals(principalStr) || isServiceClient(principalStr)) {
                log.debug("检测到服务账户: {}, 使用系统用户ID", principalStr);
                return getSystemUserId();
            }

            // 尝试转换为Long（原有逻辑）
            try {
                return Long.valueOf(principalStr);
            } catch (NumberFormatException e) {
                log.warn("principal不是数字格式的用户ID: {}, 使用系统用户ID", principalStr);
                return getSystemUserId();
            }

        } catch (Exception e) {
            log.warn("获取当前用户ID异常，使用系统用户ID", e);
            return getSystemUserId();
        }
    }

    /**
     * 判断是否是服务客户端
     */
    private boolean isServiceClient(String principal) {
        return principal.endsWith("-app") ||
                principal.endsWith("-service") ||
                principal.endsWith("-client");
    }

    /**
     * 获取系统用户ID
     */
    private Long getSystemUserId() {
        // 返回一个固定的系统用户ID
        // 可以是 0L, -1L, 或者在配置文件中配置的值
        return 0L;
    }

//    private Long getCurrentUserId() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if(authentication == null || "anonymousUser".equals(authentication.getPrincipal().toString())) {
//            return null;
//        }
//        return Long.valueOf(authentication.getPrincipal().toString());
//    }
}
